<template>
  <yd-layout class="m-address-manage">
    <!-- 顶部导航 -->
    <yd-navbar slot="navbar" :title="address.id ? '编辑地址' : '新增地址'" height=".88rem" bgcolor="#fff" color="#444" fontsize=".3rem">
      <yd-navbar-back-icon slot="left" color="#666" @click.native="$router.back()"></yd-navbar-back-icon>
    </yd-navbar>

    <div class="m-address-manage-ct">
      <yd-cell-group ref="inputGroup">
        <yd-cell-item>
          <yd-input slot="right"
            type="text" 
            v-model="address.trueName" 
            placeholder="姓名"
            :required="true"
            regex="^[\u4e00-\u9fa5_a-zA-Z0-9_]{2,10}$"
            :max="10"
            :showErrorIcon="false"
            :showSuccessIcon="false"
            :showRequiredIcon="false">
          </yd-input>
        </yd-cell-item>
        <yd-cell-item>
          <yd-input slot="right"
            type="text" 
            v-model="address.mobile" 
            placeholder="手机号码"
            :required="true"
            regex="mobile"
            :showErrorIcon="false"
            :showSuccessIcon="false"
            :showRequiredIcon="false">
          </yd-input>
        </yd-cell-item>
        <yd-cell-item>
          <yd-input slot="right"
            type="text" 
            v-model="address.addressArea" 
            placeholder="请选择所在地区"
            :required="true"
            :showClearIcon="false"
            :showErrorIcon="false"
            :showSuccessIcon="false"
            :showRequiredIcon="false"
            @click.native.stop="addressShow = true">
          </yd-input>
        </yd-cell-item>
        <yd-cell-item>
          <yd-input slot="right"
            type="text" 
            v-model="address.areaInfo" 
            placeholder="详细地址，如街道、楼牌号等"
            :required="true"
            regex="^[\u4e00-\u9fa5_a-zA-Z0-9_]{2,50}$"
            :max="50"
            :showErrorIcon="false"
            :showSuccessIcon="false"
            :showRequiredIcon="false">
          </yd-input>
        </yd-cell-item>
      </yd-cell-group>

      <yd-checkbox v-model="address.defaultBool" color="#f00385" size="16">设为默认地址</yd-checkbox>

      <yd-button-group>
        <yd-button size="large" type="primary" @click.native="onSubmit">保存</yd-button>
      </yd-button-group>
    </div>

    <yd-cityselect v-model="addressShow" :callback="addressPicker" :items="areaList" v-if="areaList.length"></yd-cityselect>
  </yd-layout>
</template>

<script>
  import { apiAddressById, apiEditAddress, apiAddAddress } from 'js/api'
  import { mapGetters, mapActions } from 'vuex'

  export default {
    data() {
      return {
        addressShow: false,
        address: {
          trueName: '',
          areaInfo: '',
          zip: '',
          telephone: '',
          mobile: '',
          defaultBool: false,
          defaultVal: 0,
          areaId: '',
          id: '',
          addressArea: ''
        }
      }
    },
    created() {
      this.address.id = this.$route.query.id
      this.fetchArea()
      // 判断是编辑还是新增，有id是编辑
      if (this.address.id) { // 编辑
        apiAddressById(this.token, this.address.id).then(data => {
          const oAddress = data.addressList && data.addressList[0]
          this.address = Object.assign({}, this.address, oAddress)
          this.address.areaInfo = oAddress.area_info
          this.address.defaultBool = oAddress.default_val == 1
          this.address.addressArea = `${oAddress.provinceName}/${oAddress.cityName}/${oAddress.areaName}`
        })
      }
    },
    methods: {
      ...mapActions(['fetchArea']),
      addressPicker(data) {
        this.address.areaId = data.itemValue3
        this.address.addressArea = `${data.itemName1}/${data.itemName2}/${data.itemName3}`
      },
      onSubmit() {
        const oInputGroup = this.$refs.inputGroup
        let isTrue = true
        oInputGroup.$children.forEach(item => {
          const oInput = item.$children[0]
          if (oInput.errorMsg) {
            isTrue = false
            this.$toast(oInput.errorMsg, () => {
              oInput.$el.children[0].focus()
            })
          }
        })
        if (!isTrue) return
        // 设置是否默认
        this.address.defaultVal = this.address.defaultBool ? 1 : 0
        // 成功操作
        if (this.address.id) { // 编辑
          apiEditAddress(this.token, this.address).then(data => {
            this.$toast('编辑成功', () => {
              this.$router.replace('/address')
            })
          })
        } else { // 新增
          apiAddAddress(this.token, this.address).then(data => {
            this.$toast('新增成功', () => {
              const redirect = decodeURIComponent(this.$route.query.redirect || '')
              if (redirect) {
                this.$router.replace(redirect)
              } else {
                this.$router.replace('/address')
              }
            })
          })
        }
      }
    },
    computed: {
      ...mapGetters(['token', 'areaList'])
    }
  }
</script>

<style lang="scss">
  .m-address-manage-ct {
    height: 100%;
    background: #fff;
    .yd-checkbox {
      padding: .3rem;
      color: #ef5c6e;
    }
  }
</style>